
//
//  TBNetWorkingTools.swift
//  新浪微博
//
//  Created by bin on 16/1/27.
//  Copyright © 2016年 XMG. All rights reserved.
//

import UIKit
import AFNetworking


class TBNetWorkTools: AFHTTPSessionManager {

    static let shareInstance: TBNetWorkTools = {
        // 注意: 指定BaseURL时一定要包含/
        let url = NSURL(string: Base_URL)
        let instance = TBNetWorkTools(baseURL: url, sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as! Set<String>
        return instance
    }()
    
    func getAccessToken(parameters: AnyObject?, success: (response: AnyObject?) -> Void){
        
//        TBNetWorkTools.shareInstance.POST("oauth2/access_token", parameters: parameters, success: success, failure: failure)
        TBNetWorkTools.shareInstance.POST("oauth2/access_token", parameters: parameters, success: { (_, response) -> Void in
            success(response: response)
            }) { (_, error) -> Void in
                print("\(error)")
        }
    }
    
    func getUserInfo(parameters: AnyObject?, success: ((task: NSURLSessionDataTask,response: AnyObject?) -> Void)?, failure: ((task: NSURLSessionDataTask?, error: NSError) -> Void)?) -> NSURLSessionDataTask?{
        //https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00zkVobCGHSkMB7e6979d99cm2WbGD&uid=157679999
        return TBNetWorkTools.shareInstance.GET("2/users/show.json", parameters: parameters, success: success, failure: failure)
        
    }
    
    func getStatus(since_id: String, max_id: String, finished: (dicts: [[String : AnyObject]]? , error: NSError?) -> Void ){
        let userAccount = TBUserAccount.loadFormFile()
        let parameters = ["access_token" : (userAccount?.access_token)!, "since_id" : since_id, "max_id" : max_id]
        
        TBNetWorkTools.shareInstance.GET("2/statuses/home_timeline.json", parameters: parameters, success: { (_, response) -> Void in
            finished(dicts: (response as! [String : AnyObject])["statuses"] as? [[String : AnyObject]], error: nil)
            
            }) { (_, error) -> Void in
                finished(dicts: nil , error: error)
        }
    }


}
